import FetchBlod from "rn-fetch-blob";

const dirs = FetchBlod.fs.dirs;
export const IMGCACHEPATH = dirs.CacheDir + '/imgs/';

export default async function downloadFiles(uriPaths, callFn){
    let len = uriPaths.length;
    if(len == 0){
        callFn(null);
    }
    for(let index = 0;index < len ;index++){
        let path = await down(uriPaths[index]);
        callFn(path,index);
    }
}

export async function downloadFile(url, name, nameIncludesExt = false) {
    return await down(url, name, nameIncludesExt);
}


function down(uri, uriName = "", nameIncludesExt = false){
    return new Promise((resolve,reject)=>{
        if (uriName == "") {
            uriName = getUriName(uri);
        } else {
            if (!nameIncludesExt) {
                uriName = uriName + "." + getUriExtName(uri);
            }
        }
        if(uriName == ""){
            resolve(null);
        }
        const path = IMGCACHEPATH+uriName;
        FetchBlod
        .config({
            fileCache : true,
            path: path
        })
        .fetch('GET', uri)
        .then((res)=>{
            resolve(uriName);
            //resolve("file://"+res.path());
        })
        .catch((e)=>{
            console.log(e);
            resolve(null);
        })
    })
    
}

function getUriExtName(uri) {
    if(uri){
        let index = uri.lastIndexOf(".");
        if(index > -1){
            return uri.substr(index+1);
        }
    }
    return "";
}

function getUriName(uri){
    if(uri){
        let index = uri.lastIndexOf("/");
        if(index > -1){
            return uri.substr(index+1);
        }
    }
    return "";
}